package com.lucy.nepu.system.draft;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.lucy.common.domain.ResponseDTO;
import com.lucy.nepu.system.draft.params.DraftCreateParams;
import com.lucy.nepu.system.draft.params.DraftQueryParams;
import com.lucy.nepu.system.period.Period;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("nepu")
@Api(tags = "草稿管理")
public class DraftController {
    @Autowired
    DraftService draftService;

    @PostMapping("drafts")
    @ApiOperation(value = "草稿新建",notes = "")
    public ResponseDTO<Object> draftCreate(@RequestBody @Validated DraftCreateParams params){
        // 获取当前登录用户
        Long userId = StpUtil.getLoginIdAsLong();
        // 草稿参数
        Draft draft = new Draft();
        BeanUtil.copyProperties(params,draft);
        draft.setUserId(userId);
        draft.setStatus(1);
        // 写入存储
        return ResponseDTO.succData(
                draftService.saveOne(draft)
        );
    }

    @DeleteMapping("drafts/{id}")
    @ApiOperation(value = "草稿删除",notes = "")
    public ResponseDTO<Object> draftDelete(@PathVariable("id") String id){
        draftService.deleteOne(id);
        return ResponseDTO.succMsg("删除成功");
    }

    @DeleteMapping("form/{formId}/drafts")
    @ApiOperation(value = "草稿删除(表单)",notes = "")
    public ResponseDTO<Object> formDraftDelete(@PathVariable("formId") String formId){
        draftService.deleteByFormId(formId);
        return ResponseDTO.succMsg("删除成功");
    }

    @GetMapping("drafts")
    @ApiOperation(value = "草稿列表",notes = "")
    public ResponseDTO<Object> draftListQuery(DraftQueryParams params){
        Sort sort;
        if("DESC".equalsIgnoreCase(params.getOrder())){
            sort = Sort.by(Sort.Direction.DESC, params.getSortBy());
        }else {
            sort = Sort.by(Sort.Direction.ASC, params.getSortBy());
        }

        // tips : 页码对应 - 1
        Pageable pageable = PageRequest.of(params.getPageNum() - 1 , params.getPageSize(), sort);

        Draft draft = new Draft();
        BeanUtil.copyProperties(params,draft, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        Example<Draft> example = Example.of(draft);
        return ResponseDTO.succData(draftService.getAll(pageable,example));
    }



}
